'use strict';

const Controller = require('egg').Controller;

class StoreController extends Controller {
    //创建
    async create() {
        let {ctx,service} = this;
        let {title,intro,status} = ctx.request.body;
        let time = new Date();
        let {uid} = ctx.info;
        if(title && intro && status){
            //1.排重
            let selectStore =await service.store.selectStore(title);
            if(selectStore.length){
                //此知识库已存在
                ctx.body = {
                    code:3,
                    msg:'此知识库已存在'
                }
            }else{
                try{
                    await service.store.create(title,intro,uid,status,time);
                    ctx.body = {
                        code:1,
                        msg:'此知识库创建成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //更新
    async update(){
        let {ctx,service} = this;
        let {title,intro,status} = ctx.request.body;
        let time = new Date();
        let {id} = ctx.params;
        if(title && intro && status && id){
            try{
                await service.store.update(title,intro,status,time,id);
                ctx.body = {
                    code:1,
                    msg:'更新成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //查询
    async index(){
        let {ctx,service} = this;
        let {uid} = ctx.info;
        let storelist = await service.store.index(uid);
        ctx.body = {
            code:1,
            data:storelist
        }
    }
    //删除
    async destroy(){
        let {ctx,service} = this;
        let {id} = ctx.params;
        if(id){
            try{
                await service.store.delete(id);
                await service.store.deleteWord(id);
                ctx.body = {
                    code:1,
                    msg:'删除成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
}

module.exports = StoreController;
